const fs = require("fs").promises;
const path = require("path");

class SessionDB {
  constructor() {}

  async set(uid, sid, message) {
    let txt;
    if (sid) {
      txt = `${sid}|${uid}|${message};`;
    } else {
      txt = `user|${uid}|${message};`;
    }
    await fs.writeFile(path.join(__dirname, "session.txt"), txt, { flag: "a" });
    return 1;
  }

  async get(uid) {
    let cont = await fs.readFile(path.join(__dirname, "session.txt"), {
      withFileTypes: true,
    });
    cont = cont.toString();
    const stripList = cont.split(";");
    const uidStrip = stripList.filter((item) => item.includes(`|${uid}|`));
    const history = [];
    // 记录上一条sid
    let temporarySid = "";
    for (let index = 0; index < uidStrip.length; index++) {
      if (uidStrip[index].includes("user|")) {
        history.push({
          role: "user",
          content: uidStrip[index].split(`|${uid}|`)[1],
        });
      } else {
        let sid = uidStrip[index].split(`|${uid}|`)[0];
        if (sid !== temporarySid) {
          temporarySid = sid;
          history.push({
            role: "assistant",
            content: uidStrip[index].split(`|${uid}|`)[1],
          });
        } else {
          history[history.length - 1].content =
            history[history.length - 1].content +
            uidStrip[index].split(`|${uid}|`)[1];
        }
      }
    }
    return history;
  }
}

module.exports = SessionDB;
